from rest_framework import serializers

from goods.models import SKU


class CartSerializer(serializers.Serializer):
    """购物车序列化器类"""
    sku_id = serializers.IntegerField(label='SKU商品ID')
    count = serializers.IntegerField(label='添加数量')
    selected = serializers.BooleanField(label='勾选状态', default=True)

    # 校验数据   校验商品id值和数量count，勾选状态并未校验
    def validate(self, attrs):
        # 检验sku_id 是否存在
        sku_id = attrs['sku_id']

        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        # 如果商品存在 检测用户所选数量是否超过最大库存量
        count = attrs['count']
        if count > sku.stock:
            raise serializers.ValidationError('商品库存不足')

        return attrs


class CartSKUSerializer(serializers.ModelSerializer):
    """购物车商品序列化器类"""
    count = serializers.IntegerField(label='数量')
    selected = serializers.BooleanField(label='是否勾选')

    class Meta:
        model = SKU
        fields = ('id', 'count', 'name', 'default_image_url', 'price', 'selected')


class CartDelSerializer(serializers.Serializer):
    """购物车删除的序列化器类"""
    sku_id = serializers.IntegerField(label='SKU商品id')

    def validate_sku_id(self, value):
        try:
            sku = SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        return value


class CartSelectSerializer(serializers.Serializer):
    """购物车全选序列化器类"""
    selected = serializers.BooleanField(label='是否全选')
